﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;

using NORM.Entity;
using NORM.SQLObject;
using NORM.Common;
using NORM.Configure;

namespace NORM.DataBase
{
    public class DataBase : IDisposable
    {
        protected int _surplusTransTime = 0;
        protected string _sql = string.Empty;
        protected string _connectionString = string.Empty;
        protected OsqlCommand Command = new OsqlCommand();
        protected DataBaseTypes _dataBaseType = DataBaseTypes.SqliteDataBase;

        /// <summary>
        /// 清理sqlstatement
        /// </summary>
        internal void sqlstatementclear()
        {            
            _sql = string.Empty;
            Command = new OsqlCommand();
        }

        protected string Join(SectionString[] SectionsString)
        {
            string rvl = string.Empty;
            foreach (var SectString in SectionsString)
            {
                rvl += SectString.ToString() + ";";
            }
            return rvl;
        }

        protected SectionString[] Parse(string ParseString)
        {
            List<SectionString> array = new List<SectionString>();
            string[] splits = ParseString.Split(';');
            foreach (string str in splits)
            {
                if (!string.IsNullOrEmpty(str))
                {
                    SectionString secstr = new SectionString(str);
                    if (secstr.Key.Equals("Data Source"))
                    {
                        secstr.Value = secstr.Value.Replace("|DataDirectory|", AppDomain.CurrentDomain.BaseDirectory);
                    }
                    if (secstr.Key.Equals("Password") || secstr.Key.Equals("Pwd"))
                    {
                        secstr.Value = EncryptDES.DecryptDES(secstr.Value);
                    }
                    array.Add(secstr);
                }

            }
            return array.ToArray();
        }

        protected void validateOqlend(OQL oql)
        {
            if (!oql.IsEnd)
            {
                oql = oql.End;
                throw new NORMException(ExceptionType.OQLExceptin, "请检查是否调用End");
            }              
        }

        public override string ToString()
        {
            return _sql;
        }

        /// <summary>
        /// 
        /// </summary>
        public string ConnectionString
        {
            get { return _connectionString; }
        }
        
        /// <summary>
        /// 
        /// </summary>
        public DataBaseTypes DataBaseType
        {
            internal set { _dataBaseType = value; }
            get { return _dataBaseType; }
        }

        /// <summary>
        /// 开启事务
        /// </summary>
        public virtual void BeginTransaction() { }

        /// <summary>
        /// 提交事务
        /// </summary>
        /// <returns></returns>
        public virtual int Commit() { return 1; }

        /// <summary>
        /// 事务回滚
        /// </summary>
        public virtual void RollBack() { }

        /// <summary>
        /// 释放资源
        /// </summary>
        public virtual void Dispose()
        {
            CacheProperties.cacheInstance.Dispose();
        }
        
        public bool TransCompleteState()
        {
            if (this._surplusTransTime > 0)
                return false;
            else
                return true;
        }

        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public virtual bool TestConnect(out string message)
        {
            message = "连接失败";
            return false;
        }

        public virtual int Execute(OQL oql) { return -1; }

        public virtual bool Insert<T>(T model) where T : EntityBase { return false; }

        public virtual bool Update<T>(T model) where T : EntityBase { return false; }

        public virtual bool Delete<T>(T model) where T : EntityBase { return false; }

        public virtual bool Delete<T>(object PrimaryKeyValue) where T : EntityBase { return false; }

        public virtual List<T> QueryList<T>(OQL oql, PageLimit page) where T : EntityBase { return new List<T>(); }

        public virtual List<T> QueryList<T>(OQL oql) where T : EntityBase { return new List<T>(); }

        public virtual T QueryObject<T>(OQL oql) where T : EntityBase { return (T)Activator.CreateInstance(typeof(T)); }

        public virtual T QueryModel<T>(object PrimaryKeyValue) where T : EntityBase { return (T)Activator.CreateInstance(typeof(T)); }

        public virtual DataTable QueryTable(OQL oql, PageLimit page = null) { return new DataTable(); }

        public virtual int Execute(CommandType cmdType, string cmdText, params OsqlParameter[] cmdParms) { return -1; }

        /// <summary>
        /// 执行SQL
        /// </summary>
        /// <param name="cmdType">命令类型 文本/存储过程</param>
        /// <param name="cmdText">命令文本</param>
        /// <param name="timeout">超时时间 单位秒 0 不限制</param>
        /// <param name="cmdParms">执行参数</param>
        /// <returns></returns>
        public virtual int Execute(CommandType cmdType, string cmdText, int timeout, params OsqlParameter[] cmdParms) { return -1; }

        public virtual DataSet QueryDataSet(CommandType cmdType, string cmdText, params OsqlParameter[] cmdParms) { return new DataSet(); }

        public virtual DataTable QueryTable(string cmdText, OsqlParameter[] cmdParms = null) { return new DataTable(); }

        public virtual DataTable QueryTable(CommandType cmdType, string cmdText, OsqlParameter[] cmdParms = null) { return new DataTable(); }

        public virtual DataTable GetTableObject(string name, DataBaseSchema schema) { return new DataTable(); }

        public virtual DataTable GetTableObject(string name) { return new DataTable(); }

        /// <summary>
        /// 获取数据库对象
        /// </summary>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public virtual DataTable GetDataBaseObject(string collectionName) { return new DataTable(); }

        /// <summary>
        /// 获取数据库对象
        /// </summary>
        /// <returns></returns>
        public virtual DataTable GetDataBaseObject() { return new DataTable(); }

        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="dataSet">数据集</param>
        /// <param name="srcTable">如 SELECT TOP 0 * FROM T </param>
        /// <returns></returns>
        public virtual bool UpdateDataSet(DataSet dataSet, string srcTable) { return false; }

        /// <summary>
        /// 获取对象依赖项
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type">1.依赖于自身,2.自身依赖于</param>
        /// <returns></returns>
        public virtual DataTable GetDependencies(string name,int type) { return new DataTable(); }

        /// <summary>
        /// 获取表索引
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public virtual DataTable GetTableIndexes(string tableName) { return new DataTable(); }

        /// <summary>
        /// 获取表的触发器
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public virtual DataTable GetTableTrigger(string tableName) { return new DataTable(); }

        /// <summary>
        /// 获取表的约束
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public virtual DataTable GetTableConstraint(string tableName) { return new DataTable(); }

        /// <summary>
        /// 创建数据库 
        /// </summary>
        /// <param name="DataBaseName">数据库名称</param>
        /// <param name="FilePath">数据文件存放位置</param>
        /// <param name="InitSize">数据库文件初始大小 单位mb</param>
        /// <param name="MaxSize">数据库文件最大 单位mb -1 不限制大小</param>
        /// <param name="Growth">数据库文件增长比例 10% 或 200mb 对于数据库文件超过2GB 推荐值200mb </param>
        /// <param name="GrowthType">增长单位 默认百分比 % 或 mb </param>
        /// <param name="Server">服务器IP地址</param>
        /// <param name="Port">数据库服务端口号 默认 1433</param>
        /// <param name="UserId">数据库登陆帐号</param>
        /// <param name="Password">数据库登陆密码</param>
        /// <param name="Message">返馈信息</param>
        public virtual void CreateDataBase(string DataBaseName, string FilePath, decimal InitSize, decimal MaxSize, decimal Growth, string GrowthType,
            string Server, string Port, string UserId, string Password, out string Message) { Message = string.Empty; }

        /// <summary>
        /// 获取上一次执行SQL影响行数
        /// </summary>
        /// <returns></returns>
        public virtual int GetLastCommandExcuteRowCount()
        {
            return -1;
        }

    }
}
